export const useStreaming = () => {
  const streamResponse = async (url, data, onChunk, onError) => {
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      });

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        // 解码流式数据

        const chunk = decoder.decode(value, { stream: true });
        // / 按行分割数据
        const lines = chunk.split("\n\n");
        for (const line of lines) {
          if (line.startsWith("data: ")) {
            try {
              // 去掉 "data: " 前缀并解析 JSON
              const jsonStr = line.replace("data: ", "");
              const parsedChunk = JSON.parse(jsonStr);

              // 调用回调函数处理数据
              if (parsedChunk.reply && onChunk) {
                onChunk(parsedChunk.reply);
              }
            } catch (error) {
              console.error("Failed to parse chunk:", line, error);
            }
          }
        }
      }
    } catch (error) {
      // 调用错误回调函数
      if (onError) {
        onError(error);
      } else {
        console.error("Error:", error);
      }
    }
  };

  return {
    streamResponse,
  };
};
